<?php

// +----------------------------------------------------------------------
// | 权限组控制器
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\controller\pay\admin;

use app\model\pos\Pos as PosModel;
use app\model\ucenter\User as UserModel;
use think\Exception;
use yicmf\builder\Edit;
use yicmf\builder\Table;
use app\controller\admin\Common;
use app\event\file\Attachment as AttachmentEvent;
use app\model\ucenter\UserMoneyLog as UserMoneyLogModel;
use app\event\ucenter\User as UserEvent;

class MoneyLog extends Common
{
    protected function initialize()
    {
        parent::initialize();
    }

    public function _filter()
    {
        $where[] = ['status', '>', -2];
        return $where;
    }

    public function index()
    {

        $statusOptions = [];

        foreach (UserMoneyLogModel::$money_type as $index => $item) {
            $statusOptions[] = [
                'id' => $index,
                'value' => $item,
            ];
        }

        $where = $this->_filter();
        $field = $this->request->param('field/a');
        if (!empty($field['is_bind'])) {
            if ($field['is_bind'] == 2) {
                $where[] = ['user_id', '!=', ''];
            } else {
                $where[] = ['user_id', '=', null];
            }
        }
        if (!empty($field['sn_start'])) {
            $where[] = ['sn', '>=', $field['sn_start']];
        }
        if (!empty($field['sn_end'])) {
            $where[] = ['sn', '<=', $field['sn_end']];
        }

        //ID 姓名 手机号 等级  变更余额  变更前  变更后 事项 时间 资金类型
        // 显示页面
        $builder = new Table();
        $builder->model(UserMoneyLogModel::class)
            ->where($where)
            ->buttonExcelImport()
            ->buttonUpdate('recharge', '充值')
            ->searchUser('用户')
//                ->suggest('高等级可以对低等级用户进行操作或者授权')
            ->searchSelect('type', '资金类型', $statusOptions)
            ->searchTextLike('memo', '备注')
            ->searchDateTimeRange('create_time', '变更时间')
            ->excel()
//            ->searchText('sn_start', '机身开始号')
//            ->searchText('sn_end', '机身结束号')
//            ->searchText('result_count', '显示总数')
//            ->keyLeftLeader('checkbox')
            ->keyId()
            ->keyUser('user_id', '用户')
            ->keyText('user.mobile', '手机号')
            ->keyText('user.level', '等级')
            ->keyText('money', '变更余额')
            ->keyText('before', '变更前')
            ->keyText('after', '变更后')
            ->keyText('memo', '备注')
            ->keyMap('type', '资金类型', UserMoneyLogModel::$money_type)
            ->keyText('order_id', '关联订单')
//				->keyUpdateTime()
            ->keyCreateTime('交易时间');
//            ->actionForbid('forbid?id={$id}', '禁用', function ($data) {
//                return 1 == $data['status'] && 1 < $data['id'];
//            });
        return $builder->fetch();
    }


    public function userHtml()
    {

        $statusOptions = [
            [
                'id' => 1,
                'value' => '未划拨'
            ],
            [
                'id' => 2,
                'value' => '已划拨'
            ]
        ];
        $where = $this->_filter();
        $builder = new Table();
        $builder->model(UserMoneyLogModel::class)
            ->where($where)
            ->setSearchPostUrl('/pay/admin/MoneyLog/userHtml', ['user_id' => $this->request->param('id')])
            ->searchDateTimeRange('create_time', '变更时间')
//                ->suggest('高等级可以对低等级用户进行操作或者授权')
//            ->searchSelect('is_bind', '划拨状态', $statusOptions)
//            ->searchText('sn_start', '机身开始号')
//            ->searchText('sn_end', '机身结束号')
//            ->searchText('result_count', '显示总数')
//            ->keyLeftLeader('checkbox')
            ->keyId()
//            ->keyText('user.nickname', '用户名')
//            ->keyText('user.mobile', '手机号')
//            ->keyText('user.level', '等级')
            ->keyText('money', '变更余额')
            ->keyText('before', '变更前')
            ->keyText('after', '变更后')
            ->keyText('memo', '备注')
            ->keyMap('type', '资金类型', UserMoneyLogModel::$money_type)
            ->keyText('order_id', '关联订单')
//				->keyUpdateTime()
            ->keyCreateTime('交易时间');
//            ->actionForbid('forbid?id={$id}', '禁用', function ($data) {
//                return 1 == $data['status'] && 1 < $data['id'];
//            });
        return $builder->fetch();
    }


    public function import()
    {
//        if($v['shareCode']){
//            $user_id = Db::name('user')->where(['shareCode'=>ltrim($v['shareCode'],'F')])->value('id');
//            if(empty($user_id)){
//                exception('该用户未发现：'.$v['shareCode']);
//            }
//            $memo = $v['platform'] . ':' . $v['mark'];
//            \app\common\model\User::money($v['money'],$user_id,$memo,66,0);
//        }
        if ($this->request->isPost()) {

            $excel_id = $this->request->param('file_id', '');

            $info = AttachmentEvent::distinguish($excel_id);
            $count = 0;
            if (is_array($info)) {
                foreach ($info as $index => $item) {
                    if ($index > 0) {

                        $user = UserModel::where('shareCode', ltrim(strtoupper($item[1]), 'F'))->find();
                        if ($user) {
                            $count++;
                            $memo = $item[2] . ':' . $item[4];
                            UserEvent::money($item[3], $user['id'], $memo, 66, $user['id']);
                        }

                    }

                }
            }
            $this->_returnSuccess('成功导入' . $count . '条信息', false);
        } else {

            $this->_returnError('请求异常', false);
        }


    }

    public function update()
    {
        if ($this->request->isPost()) {
            try {
                if ($this->request->param('id')) {
                    $group = PosModel::where('id', $this->request->param('id'))->where('store_id', $this->store['id'])->find();
                    if (!$group) {
                        throw new Exception('pos不存在');
                    }
                    $group['name'] = $this->request->param('name');
                    $group['channel_id'] = $this->request->param('channel_id');
                    $group['model'] = $this->request->param('model');
                    $group['sn'] = $this->request->param('sn');
                    $data['message'] = '保存成功';
                    $group->save();
                } else {
                    // 新增
                    $group['name'] = $this->request->param('name');
                    $group['channel_id'] = $this->request->param('channel_id');
                    $group['model'] = $this->request->param('model');

                    $sn = explode("\n", trim($this->request->param('sn')));
                    foreach ($sn as $item) {
                        if (trim($item) != '' && !PosModel::where('sn', $item)->find()) {

                            $group['sn'] = $item;
                            $insertAll[] = $group;
                        }
                    }

                    $excel_id = $this->request->param('excel_id', '');
                    $insertAll = [];


                    $pos = new PosModel();
                    $c = $pos->saveAll($insertAll);
                    $data['message'] = '新增' . count($c) . '条成功';
                }

                $data['code'] = 0;
            } catch (Exception $e) {
                $data['code'] = 1;
                $data['message'] = $e->getMessage();
            }
            if (0 === $data['code']) {
                $this->_returnSuccess($data['message']);
            } else {
                $this->_returnError($data['message'], false);
            }
        } else {
            if ($this->request->param('id')) {
                $group_id = $this->request->param('id');
                $data = PosModel::where('id', $group_id)->find();
                if (!$data) {
                    $this->_returnError('POS机不存在');
                }
            } else {
                $data = [];
            }
            $param = [];

            $default_id = 0;
            foreach (PosModel::$brands as $brand) {
                if (0 == $default_id) {
                    $default_id = $brand['id'];
                }
                $param[$brand['id']] = $brand['name'];
            }

            $builder = new Edit();
            $builder->title('POS机管理')
                ->keyRadio('channel_id', '渠道', $param, '', $default_id)
                ->keyTextInline('name', '名称')
//                    ->keyBelongTo('document.title','im/admin/Document/index','关联常见问题')
                ->keyTextInline('model', '型号');
            if ($data) {
                $builder->keyTextInline('sn', '序列号', '');
            } else {
                $builder->keyAttachment('excel_id', '批量')
                    ->keyTextArea('sn', '序列号', '支持多个，每行一个');
            }
            $builder->data($data)
                ->buttonSubmit();
            return $builder->fetch();
        }
    }

    public function recharge()
    {
        if ($this->request->isPost()) {
            try {

                $user = UserModel::where('id|mobile', $this->request->param('user_id'))->find();
                if (!$user) {
                    throw new Exception('合伙人不存在');
                }
                if ($this->request->param('type')) {
                    UserEvent::freeIncome($user, $this->request->param('amount'), $this->request->param('memo'), 88, $this->user['id']);
                }else{
                    UserEvent::money($this->request->param('amount'),$user['id'], $this->request->param('memo'), 88, $this->user['id']);
                }
                $data['code'] = 0;
                $data['message'] = '提交成功';
            } catch (Exception $e) {
                $data['code'] = 1;
                $data['message'] = $e->getMessage();
            }
            if (0 === $data['code']) {
                $this->_returnSuccess($data['message']);
            } else {
                $this->_returnError($data['message'], false);
            }
        } else {
            if ($this->request->param('user_id')) {
                $user = UserModel::where('id', $this->request->param('user_id'))->find();
                $data['nickname'] = $user['nickname'];
                $data['user_id'] = $user['id'];
            } else {
                $data = [];
            }
            $param = [];

            $builder = new Edit();
            $builder->title('充值')
                ->keyBool('type', '免手续费', '用户提现不扣除手续费')
                ->keyDecimal('amount', '金额');
            if (isset($user)) {
                $builder->keyHidden('user_id')
                    ->keyLabel('nickname', '昵称')
                    ->keyLabel('user_id', '用户ID');
            } else {
                $builder->keyTextInline('user_id', '用户手机号/ID', '');
            }

            $builder
                ->keyTextArea('memo', '备注', '');

            $builder->data($data)
                ->buttonSubmit();
            return $builder->fetch();
        }
    }


    public function transfer()
    {
        if ($this->request->isPost()) {
            try {
                if ($this->request->param('id')) {
                    $group = PosModel::where('id', $this->request->param('id'))->where('store_id', $this->store['id'])->find();
                    if (!$group) {
                        throw new Exception('pos不存在');
                    }
                    $group['name'] = $this->request->param('name');
                    $group['channel_id'] = $this->request->param('channel_id');
                    $group['model'] = $this->request->param('model');
                    $group['sn'] = $this->request->param('sn');
                    $data['message'] = '保存成功';
                    $group->save();
                } else {
                    // 新增
                    $group['name'] = $this->request->param('name');
                    $group['channel_id'] = $this->request->param('channel_id');
                    $group['model'] = $this->request->param('model');

                    $sn = explode("\n", trim($this->request->param('sn')));
                    foreach ($sn as $item) {
                        if (trim($item) != '' && !PosModel::where('sn', $item)->find()) {

                            $group['sn'] = $item;
                            $insertAll[] = $group;
                        }
                    }

                    $excel_id = $this->request->param('excel_id', '');
                    $insertAll = [];
                    if ($excel_id) {
                        $info = AttachmentEvent::distinguish($excel_id);
                        if (is_array($info)) {
                            foreach ($info as $index => $item) {
                                if ($index > 0) {
                                    if (!PosModel::where('sn', $item[2])->find()) {
                                        $group['sn'] = $item[2];
                                        $group['model'] = $item[6];
                                        unset($group['user_id']);
                                        unset($group['bind_time']);
                                        unset($group['activate_time']);
                                        if ($item[1]) {
                                            $user = UserModel::where('mobile', $item[1])->find();
                                            if ($user) {
                                                $group['user_id'] = $user['id'];
                                            }
                                        }
                                        if ($item[4]) {
                                            $group['bind_time'] = time_format(strtotime($item[4]));
                                        }
                                        if ($item[5]) {
                                            $group['activate_time'] = time_format(strtotime($item[5]));
                                        }
                                        $group['model'] = $item[7];
                                        $group['name'] = $item[6];
                                        $insertAll[] = $group;
                                    }
                                }
                            }
                        }
//                        dump(is_file($excel['path']));
                    }

                    $pos = new PosModel();
                    $c = $pos->saveAll($insertAll);
                    $data['message'] = '新增' . count($c) . '条成功';
                }

                $data['code'] = 0;
            } catch (Exception $e) {
                $data['code'] = 1;
                $data['message'] = $e->getMessage();
            }
            if (0 === $data['code']) {
                $this->_returnSuccess($data['message']);
            } else {
                $this->_returnError($data['message'], false);
            }
        } else {
            // 同步节点与菜单
            if ($this->request->param('id')) {
                $group_id = $this->request->param('id');
                $data = PosModel::where('id', $group_id)->find();
                if (!$data) {
                    $this->_returnError('POS机不存在');
                }
            } else {
                $data = [];
            }
            $param = [];

            $default_id = 0;


            $builder = new Edit();
            $builder->title('POS机管理')
                ->keyRadio('channel_id', '渠道', $param, '', $default_id)
                ->keyTextInline('name', '名称')
                ->keyTextInline('model', '型号');

            $builder->data($data)
                ->buttonSubmit();
            return $builder->fetch();
        }
    }


}
